package net.trombonium.steroid;

import java.io.IOException;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.webkit.*;
import android.content.*;

public class Surveyor extends Activity implements OnClickListener{

	private Survey survey;
	//private WebView promptView;
	private Item currentItem;
	private ContentValues values;
	private DBHelper dbHelper;
	private RecordMe recorder;
	private int surveyId;
	//private int userId;
	private static final String TAG = "Surveyor";

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		surveyId = this.getIntent().getIntExtra(Steroid.S_ID, -1);
		if(surveyId==-1){
			Log.e(TAG, "No surveyId in intent");
			finish();
		}
		Notify.clearNotification(this, surveyId);

		values = new ContentValues();
		dbHelper = new DBHelper(this);
		recorder = new RecordMe();

		survey = dbHelper.getSurvey(surveyId);
		setContentView(R.layout.survey);
		//addListeners();

		currentItem = survey.getFirstItem();
		showNextItem();
	}
	
	private void addListeners(){
		findViewById(R.id.Record).setOnClickListener(this);
		findViewById(R.id.Play).setOnClickListener(this);
		findViewById(R.id.Stop).setOnClickListener(this);
	}

	private WebView getPromptView(){
		WebView promptView = (WebView)findViewById(R.id.prompt);
		promptView.addJavascriptInterface(this, "Surveyor");
		promptView.getSettings().setJavaScriptEnabled(true);
		promptView.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
		return promptView;
	}

	private void showNextItem(){
		Response r = currentItem.getResponse(0);
		switch(r.type){
		case Response.INTEGER:
		case Response.STRING:
			//findViewById(R.id.MediaButtons).setVisibility(View.GONE);
			getPromptView().loadDataWithBaseURL("content://net.trombonium.steroid/", currentItem.getPrompt(), "text/html", "utf-8", "hi");
			break;
		case Response.AUDIO:
			//findViewById(R.id.MediaButtons).setVisibility(View.VISIBLE);
			getPromptView().loadDataWithBaseURL("content://net.trombonium.steroid/", currentItem.getPrompt(), "text/html", "utf-8", "hi");
			break;
		case Response.TOUCH:
			//findViewById(R.id.MediaButtons).setVisibility(View.GONE);
			getPromptView().loadDataWithBaseURL("content://net.trombonium.steroid/", currentItem.getPrompt(), "text/html", "utf-8", "hi");
			//need a touch handler instantiated here
			break;
		case Response.GPS:
			setResponse(GPS.location(this));
			break;
		}
		//loadData(currentItem.getPrompt(),"text/html","utf-8");
		//promptView.loadUrl("file:///android_asset/page.html");
	}

	private void saveCurrentItem(){
		for(int i=0; i<currentItem.getResponseNum(); ++i){
			Response r = currentItem.getResponse(i);
			String colname = "q" + String.valueOf(currentItem.getId()) + "_0";
			switch(r.type){
			case Response.INTEGER:
				values.put(colname, Integer.parseInt(r.value));
				break;
			case Response.STRING:
			case Response.GPS:
			case Response.TOUCH:
				values.put(colname, r.value);
				break;
			case Response.AUDIO:
				values.put(colname, recorder.getLastFile());
				break;
			default:
				//fail
			}
		}
	}

	public void setResponse(String response){
		currentItem.recordResponse(0, response);
		saveCurrentItem();
		int nextId = currentItem.getNextId(response);
		if(nextId==Item.SURVEY_END)
			endSurvey();
		else{
			currentItem = survey.getItem(nextId);
			showNextItem();
		}
	}
	
	public void setTouchResponse(int x, int y, int width, int height){
		String name = (new DBHelper(this)).getRectangle(currentItem.getId(), x, y, width, height);
		setResponse(name);
	}

	private void endSurvey(){
		boolean timeToUpload = dbHelper.recordSurvey(values, surveyId);
		if(timeToUpload){
			Intent postIntent = new Intent(this, WAInterface.class);
			postIntent.putExtra(WAInterface.TODO, WAInterface.POST_RESULTS);
			postIntent.putExtra(WAInterface.SURVEY_ID, surveyId);
			startService(postIntent);
		}
		this.finish();
	}
	
	public void mediaButton(int action){
		try{
			switch(action){
			case 0:
				recorder.record(surveyId);
				break;
			case 1:
				recorder.stop();
				break;
			case 2:
				recorder.play();
				break;
			}
		} catch(Exception e){
			e.printStackTrace();
		}
	}

	public void onClick(View v){
		switch(v.getId()){
		case R.id.Record:
			recorder.record(surveyId);
			break;
		case R.id.Stop:
			recorder.stop();
			break;
		case R.id.Play:
			try{
				recorder.play();
			} catch(Exception e){
				e.printStackTrace();
			}
			break;
		}
	}
}
